package com.zzyl.nursing.service.impl;


import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;

import java.util.List;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;

import com.zzyl.nursing.dto.DeviceDataByDayDto;

import com.zzyl.nursing.domain.Device;

import com.zzyl.nursing.dto.DeviceDataDto;
import com.zzyl.nursing.dto.IotMsgNotifyData;
import com.zzyl.nursing.dto.IotMsgService;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Map;

/**
 * 设备数据Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Resource
    private DeviceMapper deviceMapper;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 查询设备数据列表
     * @param deviceDataDto
     * @return
     */
    @Override
    public List<DeviceDataVo> selectDeviceData(DeviceDataDto deviceDataDto) {
        return deviceDataMapper.queryService(deviceDataDto);
    }

    @Override

    public List<DeviceDataVo> queryDeviceDataListByDay(DeviceDataByDayDto deviceDataByDayDto) {
        // 修正：将转换结果赋值给 start 变量
        LocalDateTime start = LocalDateTime.ofInstant(Instant.ofEpochMilli(deviceDataByDayDto.getStartTime()), ZoneId.systemDefault());
        LocalDateTime end = LocalDateTime.ofInstant(Instant.ofEpochMilli(deviceDataByDayDto.getEndTime()), ZoneId.systemDefault());

        return deviceDataMapper.queryByDay(deviceDataByDayDto.getFunctionId(), start, end, deviceDataByDayDto.getIotId());
    }

    @Override
    public List<DeviceDataVo> queryDeviceDataListByWeek(DeviceDataByDayDto deviceDataByDayDto) {
        // 1. 毫秒值转 LocalDateTime
        LocalDateTime start = LocalDateTime.ofInstant(
                Instant.ofEpochMilli(deviceDataByDayDto.getStartTime()),
                ZoneId.systemDefault()
        );
        LocalDateTime end = LocalDateTime.ofInstant(
                Instant.ofEpochMilli(deviceDataByDayDto.getEndTime()),
                ZoneId.systemDefault()
        );

        // 2. 调用 Mapper 按周统计（需实现 SQL 分组逻辑）
        return deviceDataMapper.queryByWeek(
                deviceDataByDayDto.getFunctionId(),
                start,
                end,
                deviceDataByDayDto.getIotId()
        );}

        @Transactional
        @Override
        public void batchInsertDeviceData (IotMsgNotifyData iotMsgNotifyData){

            String iotId = iotMsgNotifyData.getHeader().getDeviceId();

            Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));

            List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();

            //存储该设备数据全部服务的全部数据
            List<DeviceData> deviceDataList = new ArrayList<>();

            services.forEach(service -> {

                //存储设备其中一个服务的全部数据
                List<DeviceData> list = new ArrayList<>();

                //处理上报时间日期
                LocalDateTime eventTime = LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
                //日期时区转换
                LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                        .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                        .toLocalDateTime();

                Map<String, Object> properties = service.getProperties();
                if (CollectionUtil.isEmpty(properties)) {
                    return;
                }

                properties.forEach((key, value) -> {

                    DeviceData deviceData = DeviceData.builder()
                            .iotId(iotId)
                            .deviceName(device.getDeviceName())
                            .productKey(device.getProductKey())
                            .productName(device.getProductName())
                            .functionId(key)
                            .accessLocation(device.getRemark())
                            .locationType(device.getLocationType())
                            .physicalLocationType(device.getPhysicalLocationType())
                            .deviceDescription(device.getDeviceDescription())
                            .alarmTime(alarmTime)
                            .dataValue(value + "")
                            .build();
                    list.add(deviceData);
                });

                deviceDataList.addAll(list);

                saveBatch(list);
            });

            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, iotId, deviceDataList);


        }

        @Transactional
    @Override
    public void batchInsertDeviceData1(IotMsgNotifyData iotMsgNotifyData) {

            String iotId = iotMsgNotifyData.getHeader().getDeviceId();

            Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));

            List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();

            //存储该设备数据全部服务的全部数据
            List<DeviceData> deviceDataList = new ArrayList<>();

            services.forEach(service->{

                //存储设备其中一个服务的全部数据
                List<DeviceData> list = new ArrayList<>();

                //处理上报时间日期
                LocalDateTime eventTime = LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
                //日期时区转换
                LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                        .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                        .toLocalDateTime();

                Map<String, Object> properties = service.getProperties();
                if(CollectionUtil.isEmpty(properties)){
                    return;
                }

                properties.forEach((key,value)->{

                    DeviceData deviceData = DeviceData.builder()
                            .iotId(iotId)
                            .deviceName(device.getDeviceName())
                            .productKey(device.getProductKey())
                            .productName(device.getProductName())
                            .functionId(key)
                            .accessLocation(device.getRemark())
                            .locationType(device.getLocationType())
                            .physicalLocationType(device.getPhysicalLocationType())
                            .deviceDescription(device.getDeviceDescription())
                            .alarmTime(alarmTime)
                            .dataValue(value + "")
                            .build();
                    list.add(deviceData);
                });

                deviceDataList.addAll(list);

                saveBatch(list);
            });

            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,iotId,deviceDataList);

        }
}
